#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Project ：t-player
@File    ：EventHandle.py
@Author  ：kehao
@Date    ：2021/8/1 22:10
"""
import logging
import sys
import threading

from system_hotkey import SystemHotkey

logger = logging.getLogger()


class EventHandle(threading.Thread):
    def __init__(self, thread_id, name, player):
        threading.Thread.__init__(self)
        self.name = name
        self.threadID = thread_id
        self.player = player
        self.hk = SystemHotkey()
        self.register_key()

    def register_key(self):
        try:
            self.hk.register(('alt', 'p'), callback=lambda e: self.player.pause())
        except BaseException:
            logger.error("register key error[%s]", 'alt+p')
        try:
            self.hk.register(('alt', 's'), callback=lambda e: self.player.unpause())
        except BaseException:
            logger.error("register key error[%s]", 'alt+s')
        try:
            self.hk.register(('alt', 'n'), callback=lambda e: self.player.unload())
        except BaseException:
            logger.error("register key error[%s]", 'alt+n')
        try:
            self.hk.register(('alt', 'q'), callback=lambda e: (self.player.unload(), self.player.exit()))
        except BaseException:
            logger.error("register key error[%s]", 'alt+q')
        try:
            self.hk.register(('alt', 'up'), callback=lambda e: self.player.plus_vol())
        except BaseException:
            logger.error("register key error[%s]", 'alt+up')
        try:
            self.hk.register(('alt', 'down'), callback=lambda e: self.player.sub_vol())
        except BaseException:
            logger.error("register key error[%s]", 'alt+down')

    def run(self):
        self.help()
        while True:
            user_in = input()
            if user_in == 'p':
                self.player.pause()
            elif user_in == 's':
                self.player.unpause()
            elif user_in == 'n':
                self.player.unload()
            elif user_in == 'h':
                self.help()
            elif user_in == 'q':
                self.player.unload()
                self.player.exit()
                sys.exit(0)
            elif user_in == '+' or user_in == '=':
                self.player.plus_vol()
            elif user_in == '-':
                self.player.sub_vol()

    def help(self):
        logger.info('OPERATE LIST: *** p=>pause, s=>unpause, n=>next, q=>quit, +=>plus_vol, -=>sub_vol ***')
        logger.info('HOTKEY: *** alt+p=>pause, alt+s=>unpause, alt+n=>next, alt+q=>quit, alt+up=>plus_vol, alt+down=>sub_vol ***')
